package com.scs.application.modules.base.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.dto.WarehouseSelectDto;
import com.scs.application.modules.base.entity.Dept;
import com.scs.application.modules.base.entity.Location;
import com.scs.application.modules.base.entity.Warehouse;
import com.scs.application.modules.base.mapper.DeptMapper;
import com.scs.application.modules.base.mapper.WarehouseMapper;
import com.scs.application.modules.base.service.DeptService;
import com.scs.application.modules.base.service.LocationService;
import com.scs.application.modules.base.service.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class WarehouseServiceImpl extends BaseServiceImpl<WarehouseMapper, Warehouse> implements WarehouseService, ApplicationRunner {

    @Autowired
    private LocationService locationService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private DeptMapper deptMapper;

    @Override
    public boolean saveOrUpdate(Warehouse entity) {
        //SPD多中心仓库支持
        //验证是否已经存在中心仓库
//        int count = this.count(new QueryWrapper<Warehouse>().eq("flag_center", 1).ne("id",entity.getId()));
//        if(entity.getFlagCenter() != null && entity.getFlagCenter()) count++;
//        if (count > 1 ) {
//            throw new BusinessException(String.format("只允许存在一个中心仓库，查询，目前存在%s个", count));
//        }

        if (!entity.isNewRecord()) {
            return super.saveOrUpdate(entity);
        }
        boolean success = super.saveOrUpdate(entity);

        // 创建默认库位
        Location location = new Location();
        location.setName(entity.getName())
                .setFlagDefault(true)
                .setFullname(entity.getName())
                .setWarehouseId(entity.getId());
        locationService.saveOrUpdate(location);

        return success;
    }

    @Override
    public List<Warehouse> getListForSetWarehouse(String setTypeField,String id) {
        return baseMapper.getListForSetWarehouse(setTypeField,id);
    }

    @Override
    public Page<WarehouseSelectDto> pageForSelect(QueryContext context, Map<String, Object> userParam) {
        return this.baseMapper.pageForSelect(context.getPage(), context.getWrapper(), context.getParams(),userParam);
    }

    /**
    * @Description： 获取某个仓库的请领仓库
     *<pre>
     *     先根据warehouseId 找到对应仓库 再找对应仓库的请领仓库
     *</pre>
     *@param   warehouseId
     *@return  null||Warehouse
    */
    @Override
    public Warehouse getApplyWarehouseByWarehouseId(String warehouseId) {
        if (StringUtils.isBlank(warehouseId)) return  null;

        Warehouse warehouse = baseMapper.selectById(warehouseId);
        if (warehouse == null) throw  new BusinessException("未找到仓库，可能已被删除,仓库id:%s",warehouseId);
        if (StringUtils.isBlank(warehouse.getApplyWarehouseId())) throw  new BusinessException("仓库[%s]未配置请领仓库，请联系运营检查",warehouse.getName());

        String applyWarehouseId = warehouse.getApplyWarehouseId();
        warehouse = baseMapper.selectById(applyWarehouseId);
        if (warehouse == null) throw  new BusinessException("未找到请领仓库，可能已被删除,请领仓库id:%s",applyWarehouseId);
        return warehouse;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String creatByDept(String deptId) {
        deptService.list(Wrappers.<Dept>query().eq("office_system_code", "002"));
        List<Dept> deptList = deptService.list(
                Wrappers.<Dept>query()
                        .eq("flag_disabled", GlobalConsts.NO)
                        .eq(StringUtils.isNotBlank(deptId), "id", deptId)
                        .isNull("warehouse_id")
                        .notIn("office_system_code", Arrays.asList("001", "002"))
        );
        if (ObjectUtil.length(deptList) == 0) {
            return "没有可操作的科室";
        }


        List<Warehouse> warehouseCenterList = this.list(Wrappers.<Warehouse>query().eq("flag_center",GlobalConsts.YES_STR));
        Warehouse warehouseCenter = null;
        if (ObjectUtil.length(warehouseCenterList) != 0) {
            warehouseCenter = warehouseCenterList.get(0);
        }

        List<Warehouse> warehouseList = new ArrayList<>();
        Warehouse warehouseOne;

        // 创建默认库位
        Location locationOne;
        List<Location> locationList = new ArrayList<>();
        for (Dept dept : deptList) {
            warehouseOne = new Warehouse();
            warehouseOne.setName(dept.getName());
            warehouseOne.setAddress(warehouseOne.getName());
            if (warehouseCenter != null){
                warehouseOne.setApplyWarehouseId(warehouseCenter.getId()).setApplyWarehouseName(warehouseCenter.getName());
            }
            warehouseOne.setId(IdWorker.getIdStr());
            warehouseList.add(warehouseOne);
            dept.setWarehouseId(warehouseOne.getId()).setWarehouseName(warehouseOne.getName());
            locationOne = new Location();
            locationOne.setName(warehouseOne.getName())
                    .setFlagDefault(true)
                    .setFullname(warehouseOne.getName())
                    .setWarehouseId(warehouseOne.getId());
            locationList.add(locationOne);
        }
        this.saveBatch(warehouseList);
        deptService.updateBatchById(deptList);
        locationService.saveBatch(locationList);

        return StrUtil.format("操作成功,创建仓库数量{}个",warehouseList.size());
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Map<String,Warehouse> warehouseMapById = this.list().stream().collect(Collectors.toMap(Warehouse::getId, t -> t,(left,right) -> left));
        if (ObjectUtil.length(warehouseMapById.keySet()) > 0) {
            Map<String,Location> locationByWarehouseId = locationService.list(new QueryWrapper<Location>()
                    .eq("flag_default", "1")).stream().collect(Collectors.toMap(Location::getWarehouseId, t -> t,(left,right) -> left));
            Warehouse warehouseOne;
            Location locationOne;
            List<Location> locationList = new ArrayList<>();
            for(String id : warehouseMapById.keySet()) {
                warehouseOne = warehouseMapById.get(id);
                if (!locationByWarehouseId.containsKey(warehouseOne.getId())) {
                    locationOne = new Location();
                    locationOne.setName(warehouseOne.getName())
                            .setFlagDefault(true)
                            .setFullname(warehouseOne.getName())
                            .setWarehouseId(warehouseOne.getId());
                    locationList.add(locationOne);
                }
            }
            if (ObjectUtil.length(locationList) > 0) {
                locationService.saveBatch(locationList);
            }
        }
    }
}
